<template>
  <div class="notes-view" @click="handlePageClick">
    <header class="fixed-header">
      <div class="header-container">
        <div class="sidebar-toggle" @click.stop="toggleSidebar">
          <div class="sidebar-avatar" :style="{ backgroundImage: `url(${userInfo?.avatar})` }"></div>
        </div>
        <div class="search-button" @click.stop="openSearch">
          <van-icon name="search" size="20" />
        </div>
      </div>
    </header>

    <van-popup v-model:show="tagSidebarVisible" position="left" :style="{ height: '100%', width: '250px' }">
      <div class="sidebar-header">
        <div class="sidebar-avatar" :style="{ backgroundImage: `url(${userInfo?.avatar})` }"></div>
        <span class="sidebar-username">{{ userInfo?.username }}</span>
      </div>
      <div class="recorded-days">已记录{{
        calendarData.reduce((total, week) =>
          total + week.days.filter(day => day.hasNote).length, 0
        )
      }}天</div>
      <div class="sidebar-calendar">
        <div v-for="week in calendarData" :key="week.id" class="calendar-week">
          <div v-for="day in week.days" :key="day.date" class="calendar-day" :class="{ active: day.hasNote }">
          </div>
        </div>
      </div>
      <div class="calendar-months">
        <span class="month">7月</span>
        <span class="month">8月</span>
      </div>
      <div style="display: flex; gap: 0; padding: 0 16px 16px 0; flex-direction: column; margin-top:10px;">
        <van-button type="default" @click="navigateTo('virtual-avatar')" class="custom-cell custom-cell-noborder" plain>
          我的形象
        </van-button>
        <span class="custom-cell-divider-horizontal"></span>
        <van-button type="default" @click="navigateTo('ai-pet')" class="custom-cell custom-cell-noborder" plain>
          我的宠物
        </van-button>
      </div>
      <div class="tag-management">
        <h2 class="tag-title">全部标签</h2>
        <div v-for="(tag, index) in tags" :key="index" class="tag-item">
          <span class="tag-hash">#</span>
          <span class="tag-name">{{ tag.name }}</span>
          <van-icon name="ellipsis" @click="openTagOptions(index)" class="tag-ellipsis" />
        </div>
      </div>
      <div class="settings">设置</div>
    </van-popup>

    <van-list :finished="finished" finished-text="没有更多了" @load="onLoad" class="notes-list">
      <div v-for="(note, index) in allNotes" :key="note.id" class="note-card">
        <div class="note-header">
          <div class="note-actions">
            <span class="note-time">{{ note.data }}</span>
            <van-icon name="ellipsis" @click="openNoteOptions(index)" />
          </div>
        </div>

        <div class="note-content-layout">
          <div class="note-sticker">
            <img :src="getStickerImage(note)" alt="sticker" class="sticker-image">
          </div>
          <div class="note-tags">
            <van-tag plain class="note-tag"># {{ note.tag || '杂碎' }}</van-tag>
          </div>
          <p class="note-content" :class="{ 'content-collapsed': note.collapsed && !note.expanded }">
            {{ note.content }}
          </p>

          <div v-if="note.collapsed" class="note-expand">
            <span @click="expandNote(index)">{{ note.expanded ? '收起' : '展开' }}</span>
          </div>
          <div class="clearfix"></div>
        </div>
      </div>
    </van-list>

    <!-- 单笔记管理弹窗 -->
    <van-popup v-model:show="noteOptionsVisible" position="bottom">
      <van-cell title="删除" icon="delete" @click="deleteNote(selectedNoteIndex)" />
      <van-cell title="再次编辑" icon="edit" @click="editNote(selectedNoteIndex)" />
      <van-cell title="权限设置" icon="lock" @click="setPermissions(selectedNoteIndex)" />
    </van-popup>

    <!-- 标签管理弹窗 -->
    <van-popup v-model:show="tagOptionsVisible" position="bottom">
      <van-cell title="重命名" icon="edit" @click="renameTag(selectedTagIndex)" />
      <van-cell title="删除" icon="delete" @click="deleteTag(selectedTagIndex)" />
    </van-popup>

    <van-button class="add-record-button" icon="plus" @click="navigateToRecordEditor" />
    <PetWidget v-if="pet.avatar"/>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { Toast } from 'vant';
import PetWidget from '@/components/PetWidget.vue';
import { storeToRefs } from 'pinia';
import { useNotesStore } from '@/stores/notes';
import { useUserStore } from '@/stores/user';
import { usePetStore  } from '@/stores/pet';

const router = useRouter();
const notesStore = useNotesStore();
const petStore = usePetStore();
const { pet } = storeToRefs(petStore);
const { allNotes } = storeToRefs(notesStore);

// 用户信息
const userInfo = ref<{ username: string, avatar: string } | null>(null);

// 贴纸选择
// 替换原来的 stickerImages / getStickerImage
const STICKER_BY_TAG = {
  '杂碎': '/pyq/pyq_1.png',
  '恋爱': '/chat/lianai.jpg',
  '随笔': '/pyq/pyq_2_1.png',
  '实习': '/jyj/jyj_1.png',
  '自我探寻': '/jyj/jyj_4.png',
  '旅游': '/jyj/jyj_3.png',
  '与罗小黑的聊天': '/chat/xiaoji.png',
} as const
const DEFAULT_STICKER = STICKER_BY_TAG['杂碎']

function getStickerImage(note: { tag?: string }) {
  return (note.tag && (STICKER_BY_TAG as any)[note.tag]) || DEFAULT_STICKER
}


// 侧栏用户信息（可选）
const fetchUserInfo = async () => {
  const userStore = useUserStore();
  userInfo.value = {
    username: userStore.username,
    avatar: userStore.avatar,
  };
};

// —— 纯前端分页数据源（示例，用后端时替换为 fetch） ——
/* const MOCK_FEED = [
  { content: '今天做了 20 分钟冥想，头脑清清爽爽。', images: [], tag: '随笔' },
  { content: '公园的流浪猫靠过来蹭我，治愈！', images: ['/pyq/pyq_1.png'], tag: '杂碎' },
  { content: '读完《被讨厌的勇气》，有点开悟。', images: [], tag: '读书' },
  { content: '夜跑 5 公里，配速 5\'30"', images: ['https://via.placeholder.com/150'], tag: '运动' },
  { content: '咖啡拉花失败第 N 次 :D', images: [], tag: '生活' },
  { content: '写了点 TypeScript 工具函数，爽！', images: [], tag: '编程' },
  { content: '周末打算去逛美术馆。', images: [], tag: '计划' },
]; */

const cursor = ref(0);
const PAGE_SIZE = 2;

const loading = ref(false);
const finished = ref(false);
const noteOptionsVisible = ref(false);
const tagSidebarVisible = ref(false);
const selectedNoteIndex = ref<number>(-1);
const tagOptionsVisible = ref(false);
const selectedTagIndex = ref<number>(-1);

const calendarData = ref(
  Array.from({ length: 7 }, (_, monthIndex) => ({
    id: monthIndex + 1,
    days: Array.from({ length: 7 }, (_, dayIndex) => ({
      date: `${monthIndex + 1}-${dayIndex + 1}`,
      hasNote: Math.random() > 0.5,
    })),
  }))
);

const tags = ref([
  { name: '恋爱' },
  { name: '自我探寻' },
  { name: '旅游' },
  { name: '实习' },
]);

// 分页加载（每次不同）
const onLoad = () => {
  /* if (finished.value || loading.value) return;
  loading.value = true;
  setTimeout(() => {
    const next = MOCK_FEED.slice(cursor.value, cursor.value + PAGE_SIZE);
    if (next.length) {
      notesStore.addMany(
        next.map(item => ({
          content: item.content,
          images: item.images,
          tag: item.tag,
          collapsed: false,
          expanded: false,
          data: '2025-08-26 21:18:46',
        }))
      );
      cursor.value += next.length;
    }
    loading.value = false;
    if (cursor.value >= MOCK_FEED.length) {
      finished.value = true;
    }
  }, 500); */
};

const toggleSidebar = () => {
  tagSidebarVisible.value = true;
};

const handlePageClick = (event: MouseEvent) => {
  const target = event.target as HTMLElement;
  if (!target.closest('.van-popup') && tagSidebarVisible.value) {
    tagSidebarVisible.value = false;
  }
};

const navigateTo = (routeName: string) => {
  tagSidebarVisible.value = false;
  router.push({ name: routeName });
};

const openNoteOptions = (index: number) => {
  selectedNoteIndex.value = index;
  noteOptionsVisible.value = true;
};

const deleteNote = (index: number) => {
  notesStore.removeByIndex(index);
  noteOptionsVisible.value = false;
  Toast.success('笔记已删除');
};

const editNote = (index: number) => {
  const n = allNotes.value[index];
  if (!n) return;
  Toast(`编辑笔记: ${n.content.slice(0, 20)}...`);
  noteOptionsVisible.value = false;
};

const setPermissions = (index: number) => {
  const n = allNotes.value[index];
  if (!n) return;
  Toast(`设置权限: ${n.content.slice(0, 20)}...`);
  noteOptionsVisible.value = false;
};

const navigateToRecordEditor = () => {
  router.push({ name: 'record-editor' });
};

const openTagOptions = (index: number) => {
  selectedTagIndex.value = index;
  tagOptionsVisible.value = true;
};

const renameTag = (index: number) => {
  const newName = prompt('请输入新的标签名称', tags.value[index].name);
  if (newName) {
    tags.value[index].name = newName;
  }
  tagOptionsVisible.value = false;
};

const deleteTag = (index: number) => {
  if (confirm('确定要删除这个标签吗？')) {
    tags.value.splice(index, 1);
  }
  tagOptionsVisible.value = false;
};

const expandNote = (index: number) => {
  notesStore.toggleExpand(index);
};

const openSearch = () => {
  Toast('搜索功能开发中...');
};

onMounted(() => {
  notesStore.hydrateFromLocal();       // 1) 恢复本地
  notesStore.loadStaticDefaultsOnce(); // 2) 注入“写死”的两条（只注一次）
  fetchUserInfo();
});
</script>

<style scoped>
/* 样式保持你的版本 */
.notes-view {
  padding: 20px 20px 20px 20px;
  min-height: 100vh;
  background-color: #FFFBF0;
}

.fixed-header {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  width: 100%;
  background: #fff;
  display: flex;
  align-items: center;
  justify-content: space-between;
  z-index: 100;
  padding: 8px 16px;
}

.header-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}

.sidebar-toggle {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  border: 1px solid #ddd;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
}

.search-button {
  width: 36px;
  height: 36px;
  background: #f5f5f5;
  border-radius: 50%;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #333;
}

.note-card {
  background: #FEF7E7;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, .05);
  padding: 16px;
  margin-bottom: 16px;
  position: relative;
}

.note-header {
  display: flex;
  flex-direction: column;
  margin-bottom: 12px;
}

.note-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
  margin-bottom: 8px;
}

.note-time {
  font-size: 12px;
  color: #888;
  flex-grow: 1;
}

.note-content-layout {
  position: relative;
  margin-bottom: 12px;
  overflow: hidden;
  display: block;
}

.note-sticker {
  width: 120px;
  height: 120px;
  border-radius: 4px;
  float: left;
  margin-right: 16px;
  margin-bottom: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, .1);
  position: relative;
  overflow: hidden;
}

.sticker-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.note-tags {
  display: flex;
  margin-bottom: 4px;
  flex-wrap: wrap;
}

.note-tag {
  font-size: 13px;
  color: #8C5C2A !important;
  background: transparent !important;
  border-radius: 4px;
  padding: 0;
  border-color: transparent !important;
  font-weight: 500;
}

.note-content {
  font-size: 14px;
  color: #333;
  margin: 4px 0 10px;
  white-space: pre-wrap;
  line-height: 1.5;
  text-align: justify;
  overflow: visible;
}

.content-collapsed {
  display: -webkit-box;
  -webkit-line-clamp: 4;
  -webkit-box-orient: vertical;
  overflow: hidden;
  max-height: 120px;
  text-overflow: ellipsis;
}

.clearfix {
  clear: both;
}

.van-sidebar {
  position: fixed;
  top: 0;
  left: 0;
  height: 100%;
  width: 250px;
  background-color: #fff;
  box-shadow: 2px 0 8px rgba(0, 0, 0, .1);
  z-index: 200;
}

.add-record-button {
  position: fixed;
  bottom: 80px;
  left: 50%;
  transform: translateX(-50%);
  width: 56px;
  height: 56px;
  background-color: #c2a99f;
  color: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 4px 8px rgba(0, 0, 0, .2);
  z-index: 100;
}

.settings {
  padding: 0 0 0 16px;
  font-size: 14px;
  color: #0e0e0e;
}

.sidebar-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background-size: cover;
  background-position: center -50%;
  background-repeat: no-repeat;
  overflow: hidden;
}

.sidebar-popup {
  width: 250px;
  height: 100vh;
  /* 设置高度为屏幕高度 */
  background-color: #fff;
  box-shadow: 2px 0 8px rgba(0, 0, 0, 0.1);
}

.sidebar-header {
  display: flex;
  align-items: center;
  padding: 16px;
  border-bottom: 1px solid #ddd;
}

.sidebar-username {
  font-size: 16px;
  font-weight: bold;
  color: #333;
  margin: 10px 0 0 10px;
}

.recorded-days {
  font-size: 14px;
  text-align: left;
  margin: 10px 0 0 16px;
  font-weight: bold;
}

.sidebar-calendar {
  padding: 16px;
  display: grid;
  grid-template-rows: repeat(7, 1fr);
  /* 12 行代表 12 个月 */
  gap: 8px;
}

.calendar-week {
  display: flex;
  gap: 12px;
  /* 缩小每一行中相邻格子的间距，可根据需要调整 */
}

.calendar-day {
  width: 20px;
  /* 调整宽度 */
  height: 20px;
  /* 调整高度 */
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 4px;
  background-color: #efefef;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.calendar-day.active {
  background-color: #d59977;
  color: #fff;
}

.calendar-months {
  display: flex;
  justify-content: space-around;
  font-size: 14px;
  color: #333;
}

.month {
  padding: 4px 8px;
  color: #c2c2c2;
  border-radius: 4px;
}

.tag-management {
  padding: 0px 16px 0px 16px;
  border-radius: 8px;
}

.tag-title {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 8px;
  color: #d8d3bb;
}

.tag-item {
  display: flex;
  align-items: center;
  justify-content: flex-start;
  padding: 2px 0 12px 0;
  font-size: 18px;
  color: #333;
}

.tag-hash {
  font-size: 16px;
  color: #888;
  margin-right: 12px;
}

.tag-name {
  font-size: 16px;
  color: #333;
  margin-right: auto;
}

.tag-ellipsis {
  font-size: 22px;
  color: #888;
  cursor: pointer;
  margin-left: 12px;
}

.custom-cell {
  display: flex;
  align-items: center;
  font-size: 14px;
  color: #8C5C2A !important;
  border-radius: 10px;
}

.custom-cell van-icon {
  margin-right: 8px;
}

.custom-cell:hover {
  background-color: #f5f5f5;
}

.custom-cell-outline {
  border: 1.5px solid #222 !important;
  background: #fff !important;
  color: #222 !important;
  font-weight: 500;
  box-shadow: none !important;
}

.custom-cell-noborder {
  border: none !important;
  background: #fff !important;
  color: #222 !important;
  font-weight: 500;
  box-shadow: none !important;
}

.custom-cell-divider-horizontal {
  width: 90%;
  height: 1px;
  background: #e5e5e5;
  margin: 0 14px;
  display: block;
}

.notes-list {
  margin-top: 60px;
}

.settings {
  padding: 0px 0 0 16px;
  ;
  font-size: 14px;
  color: #0e0e0e;
}

.sidebar-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background-size: cover;
  background-position: center -50%;
  background-repeat: no-repeat;
  overflow: hidden;
}
</style>
